package cc.wanforme.st.server.config;

import jakarta.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.wanforme.st.server.exception.MunkRuntimeException;
import cc.wanforme.st.server.vo.ResMessage;
import cn.dev33.satoken.exception.NotLoginException;


/** 全局异常处理类
 * @author wanne
 * 2020年9月21日
 */
@ControllerAdvice
//@ControllerAdvice(basePackages = "cc.wanforme.munkblog") //指定包
@ResponseBody
public class GlobalExceptionHandler {
	
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(NotLoginException.class)
	public ResMessage<String> invalidArgumentsException(HttpServletRequest request,
			NotLoginException e) {
		log.error(e.getMessage(), e);
		String type = e.getType();
		
		if(NotLoginException.NOT_TOKEN.equals(type)) {
			return ResMessage.relogin("请登录！");
		} else if(NotLoginException.INVALID_TOKEN.equals(type)) {
			return ResMessage.relogin("登录无效，请重新登录！");
		} else if(NotLoginException.TOKEN_TIMEOUT.equals(type)) {
			return ResMessage.relogin("登录已失效！请重新登录");
		} else if(NotLoginException.BE_REPLACED.equals(type)) {
			return ResMessage.relogin("当前账户已在其他地方登录！");
		} else if(NotLoginException.KICK_OUT.equals(type)) {
			return ResMessage.relogin("登录已失效！请重新登录");
		} else if(NotLoginException.TOKEN_FREEZE.equals(type)) {
			return ResMessage.relogin("当前登录已冻结！");
		} else if(NotLoginException.NO_PREFIX.equals(type)) {
			return ResMessage.relogin("非法登录请求！");
		} else if(NotLoginException.DEFAULT_MESSAGE.equals(type)) {
			return ResMessage.relogin("您还没有登录，请先登录！");
		}
		
		return ResMessage.relogin("未登录或登录已失效，请重新登录！");
	}
	
	@ExceptionHandler(MunkRuntimeException.class)
	public ResMessage<String> invalidArgumentsException(HttpServletRequest request,
			MunkRuntimeException e) {
		log.error(e.getMessage(), e);
		return ResMessage.fail(e.getMessage());
	}
	
	
	
}
